package me.yangbajing.model

import org.squeryl.KeyedEntity
import org.squeryl.dsl.CompositeKey2
import org.joda.time.DateTime

import net.liftweb.common.Box

import yangbajing.persistence.SquerylEntrypoint._
import yangbajing.util.Imports.Y

object MFavorite {
  def remove(refId: String, userId: String): Box[Int] =
    Y.tryBox(transaction(Entities.favorites.deleteWhere(f => f.ref_id === refId and f.user_id === userId)))

  def insert(refId: String, userId: String): Box[MFavorite] =
    Y.tryBox(transaction(Entities.favorites insert new MFavorite(refId, userId)))

  def findOne(refId: String, userId: String): Box[MFavorite] =
    Y.tryBox(transaction(from(Entities.favorites)(f =>
      where(f.ref_id === refId and f.user_id === userId) select f).single))

  def findAllByRefId(id: String): List[MFavorite] =
    transaction(from(Entities.favorites)(f =>
      where(f.ref_id === id) select f orderBy f.created_at.desc).toList)

  def findAllByUserId(id: String): List[MFavorite] =
    transaction(from(Entities.favorites)(f =>
      where(f.user_id === id) select f orderBy f.ref_id.desc).toList)

  def size(refId: Option[String] = None, userId: Option[String] = None): Long =
    transaction(from(Entities.favorites)(f =>
      where(
        f.ref_id === refId.? and
          (f.user_id === userId.?)
      ) compute count(f.ref_id)))
}

case class MFavorite(
                      ref_id: String,
                      user_id: String,
                      created_at: DateTime = DateTime.now()) extends KeyedEntity[CompositeKey2[String, String]] {
  def id = compositeKey(ref_id, user_id)
}
